package packets;

import datatypes.MCString;

public abstract class SPacket {

	private int bc = 0;
	private byte[] bout = new byte[1000];
	
	public byte[] getBytes() {
		byte[] out = new byte[bc];
		for(int i = 0; i < bc; i++) {
			out[i] = bout[i];
		}
		return out;
	}
	
	protected SPacket(int msgcode) {
		add((byte) msgcode);
	}
	
	
	protected void add(byte b) {
		bout[bc] = b;
		bc++;
	}
	
	
	protected void add(byte[] b) {
		for(byte b_ : b) {
			bout[bc] = b_;
			bc++;
		}
	}
	
	
	protected void addShort(short value) {
		byte[] b = new byte[2];
		
		b[0] = (byte)((value >>> 8) & 0xFF);
		b[1] = (byte)((value >>> 0) & 0xFF);
		
		add(b);
	}
	

	protected void addInt(int value) {
		byte[] b = new byte[4];
		  b[0] = (byte)((value >>> 24) & 0xFF);
		  b[1] = (byte)((value >>> 16) & 0xFF);
		  b[2] = (byte)((value >>>  8) & 0xFF);
		  b[3] = (byte)((value >>>  0) & 0xFF);

		add(b);
	}
	

	protected void addFloat(float value) {
		addInt(Float.floatToIntBits(value));		
	}
	
	
	
	protected void addLong(long value) {
	    byte[] b = new byte[ 8 ];

	    b[0] = (byte)(value >>> 56);
	    b[1] = (byte)(value >>> 48);
	    b[2] = (byte)(value >>> 40);
	    b[3] = (byte)(value >>> 32);
	    b[4] = (byte)(value >>> 24);
	    b[5] = (byte)(value >>> 16);
	    b[6] = (byte)(value >>>  8);
	    b[7] = (byte)(value >>>  0);

	    add(b);
	}
	
	

	protected void addDouble(double value) {
		addLong(Double.doubleToLongBits(value));
	}
	
	
	
	protected void addString(String str) {
		add(MCString.toBytesWithLength(str));
	}

}
